using System.Collections.Generic;
using System.IO;
using Comdiv.Extensions;
using Comdiv.Model;
using Comdiv.Model.Interfaces;
using Comdiv.Logging;
using Comdiv.Application;
using Comdiv.Persistence;
using Comdiv.Inversion;
using Comdiv.Security.Acl;
using Comdiv.Conversations;
using Comdiv.IO;
using Comdiv.Security;
using System.Linq;


namespace wikiviewer.Controllers{
    public class WikiRender{
        public WikiRender(string page, string root, IWikiFormatter[] formatters ){
            this.Page = page;
            this.Root = root;
            this.Formatters = formatters;
        }

        public string GetSidebarName(){
            return cache.get("getsidebarname", () =>{
                                                   var src = GetSource();
                                                   if (src.noContent()) return "";
                                                   return src.find(@"\#sidebar\s+(\w+)", 1);
                                               }, true);
        }


        public WikiRender GetSideBar(){
            return cache.get("getsidebar", () => new WikiRender(GetSidebarName(), Root, Formatters), true);
        }

        public IWikiFormatter[] Formatters { get; set; }

        public string Root { get; set; }

        public string Page { get; set; }


        IDictionary<string ,object > cache = new Dictionary<string, object>();

        public bool HasPage(){
            return cache.get("haspage()", () => {
                                              if (Page.noContent()) return false;
                                              return File.Exists(Root.addpath(Page + ".wiki"));
                                          }, true);
        }
        public string GetWikiPage(){
            return cache.get("getwikipage()", () =>{
                                                  if (!HasPage()) return "";
                                                  var result = GetSource();
                                                  foreach (var formatter in Formatters.OrderBy(x => x.Idx)){
                                                      result = formatter.Process(result);
                                                  }
                                                  return result;
                                              }, true);
        }

        public string GetSource(){
            return cache.get("getsource()", () => {
                                                return File.ReadAllText(Root.addpath(Page + ".wiki"));
                                            }, true);
            
        }
    }
}